<template>
    <div>
        <!-- 课时管理 -->
        <el-drawer
            title="课时管理"
            :visible="drawer == 'course'"
            direction="rtl"
            size="70%"
            :before-close="handleClose"
        >
            <div class="content">
                <div class="row ali_cen ju_bet courseBox">
                    <div>课时总数：{{ chapterList.length }}</div>
                    <div class="row ali_cen">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleAddCourse('all', true)"
                            >批量导入</el-button
                        >
                        <el-button
                            type="success"
                            style="margin-right:10px"
                            size="small"
                            @click="handleAddCourse('all')"
                            >添加课时</el-button
                        >
                        <el-dropdown @command="selectTitleType" trigger="click">
                            <el-button size="small">
                                添加章/节<i
                                    class="el-icon-arrow-down el-icon--right"
                                ></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="1"
                                    >添加章</el-dropdown-item
                                >
                                <el-dropdown-item command="2"
                                    >添加节</el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </div>
                <draggable
                    class="list-group"
                    tag="ul"
                    v-model="chapterList"
                    v-bind="dragOptions"
                    :move="onMove"
                    @start="isDragging = true"
                    @end="isDragging = false"
                >
                    <transition-group type="transition" :name="'flip-list'">
                        <div
                            v-for="(element, k) in chapterList"
                            :key="element.order"
                            class="row ali_cen"
                            style="margin-bottom:20px"
                            v-if="!element.hide"
                        >
                            <div
                                class="line"
                                :style="{
                                    width: element.level * 20 + 'px'
                                }"
                            ></div>
                            <div class="list-group-item row ali_cen ju_bet">
                                <!-- <i :class="element.fixed? 'fa fa-anchor' : 'glyphicon glyphicon-pushpin'" @click=" element.fixed=! element.fixed" aria-hidden="true"></i> -->
                                <div>
                                    <i
                                        class="el-icon-arrow-down"
                                        style="margin-right:10px"
                                        @click="changeDragger(element, k)"
                                        v-if="element.level < 3"
                                    ></i>
                                    <span v-if="element.level == 0"
                                        >第{{ element.levelIndex }}章</span
                                    >
                                    <span v-else-if="element.level == 1"
                                        >第{{ element.levelIndex }}节</span
                                    >
                                    <span v-else
                                        >课时{{ element.levelIndex }}</span
                                    >
                                    :{{ element.title }}
                                </div>
                                <div>
                                    <template v-if="element.level == 0">
                                        <el-dropdown
                                            trigger="click"
                                            @command="
                                                selectTitleType(
                                                    $event,
                                                    element,
                                                    k
                                                )
                                            "
                                        >
                                            <i
                                                class="el-icon-plus"
                                                style="margin-right:20px"
                                            ></i>

                                            <el-dropdown-menu slot="dropdown">
                                                <el-dropdown-item command="5"
                                                    >添加节</el-dropdown-item
                                                >
                                                <el-dropdown-item command="6"
                                                    >添加课时</el-dropdown-item
                                                >
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </template>
                                    <i
                                        class="el-icon-plus"
                                        style="margin-right:20px"
                                        title="添加课时"
                                        v-if="element.level == 1"
                                        @click="handleAddCourse(k)"
                                    ></i>
                                    <i
                                        class="el-icon-edit"
                                        style="margin-right:20px"
                                        title="修改课时"
                                        v-if="element.level == 2"
                                        @click="editCourse(element, k)"
                                    ></i>
                                    <el-dropdown
                                        trigger="click"
                                        @command="
                                            selectTitleType($event, element, k)
                                        "
                                    >
                                        <i class="el-icon-more"></i>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item command="3"
                                                >重命名</el-dropdown-item
                                            >
                                            <el-dropdown-item command="4"
                                                >删除</el-dropdown-item
                                            >
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </div>
                        </div>
                    </transition-group>
                </draggable>
            </div>
        </el-drawer>
        <!-- 添加课或者节 -->
        <el-dialog :visible="dialogFormVisible" class="dialogForm">
            <div slot="title">
                {{ titleForm.chapterId ? "修改 " : "创建 " }}
                {{ titleType == 1 ? "章" : "节" }}
            </div>
            <el-form :model="titleForm">
                <el-form-item
                    :label="titleType == 1 ? '章 标题' : '节 标题'"
                    label-width="120px"
                >
                    <el-input
                        v-model="titleForm.title"
                        autocomplete="off"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetTitle">取 消</el-button>
                <el-button type="primary" @click="submitChapter"
                    >确 定</el-button
                >
            </div>
        </el-dialog>
        <!-- 添加课时 -->
        <course
            :visible.sync="addCourse"
            :courseId="courseId"
            :chapterId.sync="chapterId"
            @getLesson="getLesson"
            :multiple="multiple"
        ></course>
    </div>
</template>
<script>
import {
    addEduCourse,
    delEduCourse,
    getEduCourse,
    listEduCourse,
    updateEduCourse,
    putChapter,
    postChapter,
    postSort,
    delChapter,
    chapterList
} from "@/api/edu/service";
import draggable from "vuedraggable";
import course from "../components/course.vue";
export default {
    name: "Config",
    components: {
        course,
        draggable
    },
    data() {
        return {
            editable: true,
            isDragging: false,
            delayedDragging: false,
            dragOptions: {
                animation: 0,
                group: "description",
                disabled: false,
                ghostClass: "ghost"
            },
            titleForm: {
                title: ""
            },
            dialogFormVisible: false,
            titleType: 1,
            currentRow: {},
            // 添加课时弹窗
            addCourse: false,
            chapterList: [],
            courseId: "",
            lessonIndex: 0,
            multiple: false,
            // 课时id
            chapterId: ""
        };
    },
    props: ["drawer", "courseId"],
    watch: {
        isDragging(newValue) {
            if (newValue) {
                this.delayedDragging = true;
                return;
            }
            this.$nextTick(() => {
                this.delayedDragging = false;
            });
            // console.log(this.chapterList);
            this.sortCourse();
        },
        drawer() {
            if (this.drawer == "course") {
                chapterList(this.courseId).then(res => {
                    let type = ["chapter", "unit", "lesson"];
                    let levelIndex = {
                        chapter: 0,
                        unit: 0,
                        lesson: 0
                    };
                    res.data.list.forEach((item, i) => {
                        item.hide = false;
                        item.order = i + 1;
                        item.level = type.indexOf(item.type);
                        if (
                            i >= 1 &&
                            item.level != res.data.list[i - 1].level &&
                            item.level != 0
                        ) {
                            levelIndex[item.type] = 0;
                        }

                        levelIndex[item.type]++;
                        item.levelIndex = levelIndex[item.type];
                    });
                    this.chapterList = res.data.list;
                });
            }
        }
    },
    created() {},
    methods: {
        selectTitleType(command, data, i) {
            if (command <= 2) {
                this.addTitle(command);
            }
            if (command == 5) {
                this.addTitle(command, data, i, "parentChapter");
            }
            if (command == 6) {
                this.handleAddCourse(i);
            }
            if (command == 3) {
                // 章节重命名
                let type;
                if (data.type == "chapter") {
                    type = 1;
                }
                if (data.type == "unit") {
                    type = 2;
                }
                this.addTitle(type, data, i);
            }
            if (command == 4) {
                this.$confirm("确认删除吗？", "", {
                    type: "error"
                }).then(_ => {
                    console.log(data);
                    delChapter(this.courseId, data.chapterId).then(res => {
                        if (res.code == 200) {
                            this.chapterList.splice(i, 1);
                        }
                    });
                });
            }
        },
        // 添加修改课时
        getLesson(data) {
            console.log(this.lessonIndex);
            let type = ["chapter", "unit", "lesson"];

            if (data.length) {
                data.forEach((item, i) => {
                    item.hide = false;
                    item.order = this.chapterList.length - 1 + i;
                    item.level = type.indexOf(item.type);
                    this.chapterList.push(item);
                });
            } else {
                data.hide = false;
                data.order = this.chapterList.length - 1;
                data.level = type.indexOf(data.type);
                // 修改则不新增
                console.log(data);
                console.log(this.lessonIndex);
                // 修改课时
                if (data.editType) {
                    this.chapterList[this.lessonIndex - 1] = data;
                } else {
                    // 章节下修改课时
                    if (this.lessonIndex != 0) {
                        this.chapterList.splice(this.lessonIndex, 0, data);
                    } else {
                        // 直接新增课时
                        this.chapterList.push(data);
                    }
                }
            }

            this.lessonIndex = 0;
            this.multiple = false;
            this.sortCourse();
        },
        onMove({ relatedContext, draggedContext }) {
            const relatedElement = relatedContext.element;
            const draggedElement = draggedContext.element;
            return (
                (!relatedElement || !relatedElement.fixed) &&
                !draggedElement.fixed
            );
        },
        // 关闭抽抽屉
        handleClose(done) {
            // this.drawer = "";
            this.$emit("update:drawer", "");
            // done();
        },
        // 添加章或节
        addTitle(type, data, i, parentChapter) {
            this.titleType = type;
            this.dialogFormVisible = true;
            if (data) {
                this.titleForm.title = data.title;
                this.titleForm.chapterId = data.chapterId;
                this.titleForm.index = i;
                if (parentChapter) {
                    this.titleForm.parentChapter = parentChapter;
                }
            }
        },
        // 添加课时
        handleAddCourse(k, multiple) {
            this.addCourse = true;
            if (k != "all") {
                this.lessonIndex = k + 1;
            }
            this.multiple = multiple ? true : false;
        },
        // 修改课时
        editCourse(data, k) {
            this.addCourse = true;
            this.lessonIndex = k + 1;
            this.chapterId = data.chapterId;
        },
        // 隐藏当前章下面的节和课时
        changeDragger(data, index) {
            let level;
            for (let i = index + 1; i < this.chapterList.length; i++) {
                if (data.level == this.chapterList[i].level) {
                    break;
                    return;
                }
                if (i >= index) {
                    if (this.chapterList[i].level > data.level) {
                        this.chapterList[i].hide = !this.chapterList[i].hide;
                        level = this.chapterList[i].level;
                    }
                    if (this.chapterList[i].level < level) {
                        break;
                    }
                }
            }
        },
        // 修改新增章或节
        submitChapter() {
            let data = {
                type: this.titleType == 1 ? "chapter" : "unit",
                title: this.titleForm.title
            };
            if (this.titleForm.chapterId && !this.titleForm.parentChapter) {
                data.chapterId = this.titleForm.chapterId;
                // 修改
                putChapter(this.courseId, data).then(res => {
                    if (res.code != 200) {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                        return false;
                    }
                    this.chapterList[this.titleForm.index].title =
                        res.data.title;
                    this.resetTitle();
                });
                return false;
            }
            postChapter(this.courseId, data).then(res => {
                if (res.code != 200) {
                    this.$message({
                        message: res.msg,
                        type: "error"
                    });
                    return false;
                }
                let data = res.data;
                let type = ["chapter", "unit", "lesson"];
                data.hide = false;
                data.order = this.chapterList.length - 1;
                data.level = type.indexOf(data.type);
                if (this.titleForm.parentChapter) {
                    // 给点击的，新增
                    this.chapterList.splice(this.titleForm.index + 1, 0, data);
                } else {
                    // 直接新增
                    this.chapterList.push(data);
                }
                this.sortCourse();
                this.resetTitle();
            });
        },
        // 重置title表单
        resetTitle() {
            this.titleForm = {
                title: ""
            };
            this.dialogFormVisible = false;
        },
        sortCourse() {
            let chapterIds = [];
            let levelIndex = {
                chapter: 0,
                unit: 0,
                lesson: 0
            };
            this.chapterList.forEach((item, i) => {
                if (
                    i >= 1 &&
                    item.level != this.chapterList[i - 1].level &&
                    item.level != 0
                ) {
                    levelIndex[item.type] = 0;
                }
                levelIndex[item.type]++;

                item.levelIndex = levelIndex[item.type];
                chapterIds.push(item.chapterId);
            });
            this.lessonIndex = 0;
            // 修改章节顺序
            postSort(this.courseId, {
                chapterIds
            });
        }
    }
};
</script>
<style lang="scss">
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
    overflow: auto;
}
/*2.隐藏滚动条，太丑了*/
.el-drawer__container ::-webkit-scrollbar {
    display: none;
}
.dialogForm {
    display: block;
    .el-dialog {
        margin-top: 15vh !important;
    }
}
</style>
